<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted, onUpdated, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import MeScroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}
const forSys = proxy.$Sys || []
const forInit = proxy.$Init || {}
const forFees = proxy.$Fees || []

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const user = reactive({
  info: '列表管理',
  btnTxt: '发布商机',
  // ----
  releaseNum: Number(logUser.opport_views) > 0 ? logUser.opport_views : 0,
  // ----
  storePayId: 0,
  storeFeeId: 'marketing',
  storeFeeVal: 0,
  storeFeeUnit: '',
  storeFeeUse: true,
  isStore: Number(logUser.is_store) === 1,
  // ----
  opportPayId: 0,
  opportFeeId: 'publishBusi',
  opportFeeVal: 0,
  opportFeeGive: 0,
  opportFeeUse: true,
  // ----
  power: 2,
  forAdm: String(proxy.$Phone) === String(logUser.telphone)
})
// ----
const forFreeTwo = 9 / 5
const setTrueStyleTwo = ref({})
const forFreeThree = 1
const setTrueStyleThree = ref({})
// ----
const fold = reactive({
  count: 3,
  height: 0,
  info: '',
  class: ''
})
// ----
let forSortNum = 0
// --mescroll--
let noData = proxy.$Global.noData
let mescroll = null
const items = ref([])

/* ---- */
const preImg = ref()
const layer = ref()
const layerBox = ref()
const layerLoading = ref()

/* ---- */
const getTrueStyle = () => {
  if (document.querySelector('.LUR-img-two')) {
    const imgEL = document.querySelector('.LUR-img-two')
    const imgRatio = forFreeTwo
    setTrueStyleTwo.value = { height: `${Math.round(imgEL.offsetWidth / imgRatio)}px` }
  }
  if (document.querySelector('.LUR-img-three')) {
    const imgEL = document.querySelector('.LUR-img-three')
    const imgRatio = forFreeThree
    setTrueStyleThree.value = { height: `${Math.round(imgEL.offsetWidth / imgRatio)}px` }
  }
}
// ----
const getCurrencyInfo = async (callback) => {
  fold.height = proxy.$refs.forTrueHeight.offsetHeight
  // --获取系统设置无数据提示--
  const noDataItems = forSys.filter((item) => { return String(item.name) === 'market_noData' })
  if (Number(noDataItems.length) === 1) {
    proxy.$Myfun.getJsonData(noDataItems[0].value, (resJson) => {
      if (Array.isArray(resJson)) {
        resJson.some((item, index) => {
          if (String(item.id) === 'busiNews' && Number(item.desc.length) > 0) noData = proxy.$Myfun.setText(item.desc)
        })
      }
    })
  }
  // --获取购买市场营销信息--
  forFees.some((item) => {
    if (String(item.id) === String(user.storeFeeId)) {
      user.storeFeeVal = Number(item.amount)
      user.storeFeeUnit = item.typeText
      user.storeFeeUse = item.isOpenUse
    }
  })
  // --购买发布数信息--
  forFees.some((item) => {
    if (String(item.id) === String(user.opportFeeId)) {
      user.opportFeeVal = Number(item.amount)
      user.opportFeeGive = item.give
      user.opportFeeUse = item.isOpenUse
    }
  })
  // ----
  if (user.isStore || !user.storeFeeUse || user.forAdm) user.power = 3
  // ----
  callback && callback()
}
// --getData--
const startMeScroll = () => {
  mescroll = new MeScroll(proxy.$refs.dataScroll, {
    up: {
      callback: getListData,
      isBounce: false,
      page: { num: 0, size: 10 },
      htmlNodata: '<p class="upwarp-nodata">-- 到底啦 --</p>',
      noMoreSize: 10,
      toTop: {
        src: '/pics/mescroll-totop.png',
        offset: 1000
      },
      empty: {
        warpId: proxy.$refs.dataList,
        tip: noData
      }
    }
  })
}
const getListData = (page) => {
  getListDataFromNet({
    forUrl: 'opport/index',
    forData: {
      params: {
        'OpportSearch[dealer_id]': logUser.id,
        // ----
        sort: 'SORT_DESC',
        // ----
        page: page.num,
        PageSize: page.size
      }
    }
  }, page.num, page.size, (curPageData) => {
    setListData(curPageData).then((result) => {
      mescroll.endSuccess(curPageData ? curPageData.length : 0, true)
      items.value = items.value.concat(result)
      // ----
      nextTick(() => { getTrueStyle() })
    })
  }, (resMsg) => {
    mescroll.endErr()
    proxy.$Myfun.forToast(layer.value, 'open', resMsg)
  })
}
const getListDataFromNet = (option, pageNum, pageSize, successCallback, errorCallback) => {
  if (Number(pageNum) === 1) {
    if (document.querySelector('.upwarp-nodata')) { document.querySelector('.upwarp-nodata').style.visibility = 'hidden' }
    items.value = []
  }
  // ----
  proxy.$http.get(option.forUrl, option.forData).then((res) => {
    if (Number(pageNum) === 1 && Number(res.items.length) > 0) forSortNum = res.items[0].sort_num
    // ----
    successCallback && successCallback(res.items)
  }).catch((err) => { errorCallback && errorCallback(err) })
}
const getFoldState = () => {
  return new Promise((resolve, reject) => {
    nextTick(() => {
      const curFoldH = proxy.$refs.forTrueHeight.offsetHeight
      if (Number(curFoldH / fold.height) > Number(fold.count)) {
        resolve(true)
      } else {
        resolve(false)
      }
    })
  })
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    let advItems = []
    const allItems = []
    await proxy.$Myfun.getJsonData(item.image, (resJson) => {
      resJson.forEach((theItem) => {
        allItems.push({
          msrc: theItem.image,
          src: theItem.image,
          width: theItem.width,
          height: theItem.height,
          alt: ''
        })
      })
      // ----
      if (Number(resJson.length) > 0) advItems = resJson.splice(0, 3)
    })
    // ----
    const fotBtnTxt = (Number(item.is_show) === 1) ? '隐藏' : '显示'
    // ----
    let forFold = false
    fold.info = proxy.$Myfun.setText(item.description)
    if (Number(advItems.length) === 1) fold.class = 'list-li-one'
    await getFoldState().then((result) => { forFold = result })
    // ----
    let forCheck = false
    let forCheckTxt = '待审核'
    let forCheckStyle = 'xw-color-5'
    if (Number(item.status) === 1) {
      forCheck = true
      forCheckTxt = '已审核'
      forCheckStyle = 'xw-color-1'
    }
    // ----
    newItems.push({
      id: item.id,
      // ----
      dealer_id: item.dealer_id,
      // ----
      name: proxy.$Myfun.setText(item.name),
      desc: fold.info,
      imgs: advItems,
      advs: allItems,
      date: proxy.$Myfun.getDateShort(item.updated_at),
      views: item.views || 0,
      // ----
      isShow: item.is_show,
      btnTxt: fotBtnTxt,
      // ----
      isFold: forFold,
      // ----
      isCheck: forCheck,
      checkTxt: forCheckTxt,
      checkStyle: forCheckStyle,
      // ----
      sortNum: forSortNum
    })
    // ----
    fold.info = ''
    fold.class = ''
  }
  return newItems
}
const divScroll = (event) => { proxy.$Myfun.setImgToTop() }
// ----
const getAuditFun = (type, item, event) => {
  if (Number(user.power) === 2) {
    const options = {
      type: 6,
      maxCount: 500,
      title: '感谢支持【万域商友会】',
      content: '请交会费：' + user.storeFeeVal.toFixed(2) + '元/' + user.storeFeeUnit,
      button: [{
        text: proxy.$Global.layer.btnCancel
      }, {
        text: '我来交费',
        class: 'xw-color-24',
        callback: (count) => {
          layerBox.value.close()
          // ----
          const lookGiveNum = forInit.look_num || 0
          const releaseGiveNum = forInit.release_num || 0
          const forToPay = { payType: user.storeFeeId, regType: 'jobs', payId: user.storePayId, payIdKey: 'jobs_id', payCount: count }
          const forExtend = { name: 'TransitPage', opts: { forAttr: 'is_store,dealer_views,opport_views', forVal: '1,' + Number(count * lookGiveNum) + ',' + Number(count * releaseGiveNum), forType: 'shopFee' } }
          proxy.$Myfun.openPage(proxy, 'push', 'PaySys', { toPay: JSON.stringify(forToPay), exTend: JSON.stringify(forExtend) })
        }
      }]
    }
    proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
    return false
  }
  // ----
  if (Number(type) === 1 && user.opportFeeUse && !user.forAdm) {
    let options = {}
    switch (Number(user.releaseNum)) {
      case 0: {
        options = {
          title: '你还可以发布<font color="#ff5722">' + user.releaseNum + '</font>条商机信息',
          content: '购买：' + user.opportFeeVal.toFixed(2) + '元/' + user.opportFeeGive + '条',
          button: [{
            text: proxy.$Global.layer.btnCancel
          }, {
            text: '我要购买',
            class: 'xw-color-24',
            callback: () => {
              layerBox.value.close()
              // ----
              const forToPay = { payType: user.opportFeeId, regType: 'jobs', payId: user.opportPayId, payIdKey: 'jobs_id', payAttr: 'opport_views' }
              proxy.$Myfun.openPage(proxy, 'push', 'PaySys', { toPay: JSON.stringify(forToPay) })
            }
          }]
        }
        break
      }
      default: {
        const forItem = item || {}
        options = {
          title: '你还可以发布<font color="#ff5722">' + user.releaseNum + '</font>条商机信息',
          content: '是否确定发布',
          button: [{
            text: proxy.$Global.layer.btnCancel
          }, {
            text: '我要发布',
            class: 'xw-color-24',
            callback: () => {
              layerBox.value.close()
              // ----
              proxy.$Myfun.openPage(proxy, 'push', 'SelfOpportAdm', { id: forItem.id })
            }
          }]
        }
      }
    }
    proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
    return false
  }
  // ----
  switch (Number(type)) {
    case 1: {
      const forItem = item || {}
      proxy.$Myfun.openPage(proxy, 'push', 'SelfOpportAdm', { id: forItem.id })
      break
    }
    case 2: {
      if (Number(item.advs.length) > 0) {
        const curEL = event.currentTarget
        const options = {
          actElement: curEL,
          addopt: {
            loop: true,
            dataSource: item.advs
          }
        }
        proxy.$Myfun.isIndepth(preImg.value, 'openPhotoSwipe', options)
      }
      break
    }
    case 3: {
      const options = {
        content: proxy.$Global.layer.conDel,
        button: [{
          text: proxy.$Global.layer.btnCancel
        }, {
          text: proxy.$Global.layer.btnDel,
          class: 'xw-color-24',
          callback: async () => {
            layerBox.value.close()
            // ----
            proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
            // ----
            if (Number(item.advs.length) > 0) {
              const opts = {
                region: proxy.$Global.aoss.region,
                bucket: proxy.$Global.aoss.bucket,
                accessKeyId: proxy.$Global.aoss.accessKeyId,
                accessKeySecret: proxy.$Global.aoss.accessKeySecret
              }
              const imgArr = item.advs
              for (let i = 0; i < Number(imgArr.length); i++) {
                await proxy.$OssUp.ossDelete(opts, imgArr[i].name)
              }
            }
            // ----
            await proxy.$http.delete('opport/delete?id=' + item.id, {
              config_id: userInfo.config_id,
              openid: userInfo.openid
            }).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
            // ----
            proxy.$Myfun.disLoading(layerLoading.value, 'close')
            mescroll.scrollTo(0)
            mescroll.resetUpScroll()
          }
        }]
      }
      proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      break
    }
    case 4: {
      proxy.$http.patch('opport/update?id=' + item.id, {
        sort_num: Number(item.sortNum + 1),
        // ----
        config_id: userInfo.config_id,
        openid: userInfo.openid
      }).then((res) => {
        mescroll.scrollTo(0)
        mescroll.resetUpScroll()
      }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
      break
    }
    case 5: {
      if (!item.isCheck) return false
      // ----
      let forCon = '是否确定显示'
      let forBtnTxt = '确定显示'
      let curField = 1
      let forItemBtnTxt = '隐藏'
      if (Number(item.isShow) === 1) {
        forCon = '是否确定隐藏'
        forBtnTxt = '确定隐藏'
        curField = 0
        forItemBtnTxt = '显示'
      }
      // ----
      const options = {
        content: forCon,
        button: [{
          text: proxy.$Global.layer.btnCancel
        }, {
          text: forBtnTxt,
          class: 'xw-color-24',
          callback: () => {
            layerBox.value.close()
            // ----
            proxy.$http.patch('opport/update?id=' + item.id, {
              is_show: curField,
              // ----
              config_id: userInfo.config_id,
              openid: userInfo.openid
            }).then((res) => {
              item.isShow = curField
              item.btnTxt = forItemBtnTxt
            }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
          }
        }]
      }
      proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      break
    }
  }
}

/* ---- */
onMounted(() => {
  getCurrencyInfo(() => {
    // --创建MeScroll对象--
    setTimeout(() => { startMeScroll() }, 500)
  })
})
onUpdated(() => { nextTick(() => { proxy.$Myfun.setSectionH() }) })
onBeforeRouteLeave(() => { if (mescroll) mescroll.destroy() })
</script>

<template>
  <div>
    <header class="xw-bg-gray">
      <div class="forTop xw-flex xw-flex-align">
        <div class="TOP-title xw-flex-W1">{{user.info}}</div>
        <span class="TOP-submit xw-WBlue xw-radius-3 TOP-Lfg" @click="getAuditFun(1)">{{user.btnTxt}}</span>
      </div>
    </header>
    <div class="xw-section">
      <div ref="dataScroll" class="mescroll" @scroll="divScroll">
        <ul class="list-user xw-flex xw-flex-column" ref="dataList">
          <li class="xw-bg-white xw-radius-3" v-for="(item, index) in items"><a>
            <div class="LUR-title xw-ellipsis-2">{{item.name}}</div>
            <div class="LUR-con xw-flex">
              <div class="LUR-img-one xw-radius-3" @click="getAuditFun(2, item, $event)" v-if="Number(item.imgs.length) === 1"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + item.imgs[0].image + ')' }"></div></div>
              <div class="LUR-desc xw-flex-W1 xw-flex" v-if="item.desc">
                <input type="checkbox" :id="'check_' + index" class="xw-fold-handle"/>
                <div class="xw-fold-text">
                  <label class="xw-fold-btn" :for="'check_' + index" v-if="item.isFold"></label>
                  {{item.desc}}
                </div>
              </div>
            </div>
            <dl class="LUR-advs xw-float" @click="getAuditFun(2, item, $event)" v-if="Number(item.imgs.length) > 1">
              <template v-if="Number(item.imgs.length) === 2">
              <dd :class="'xw-float-W' + Number(item.imgs.length)" v-for="(son, num) in item.imgs">
                <div class="LUR-img-two" :style="setTrueStyleTwo"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + son.image + ')' }"></div></div>
              </dd>  
              </template>
              <template v-if="Number(item.imgs.length) >= 3">
              <dd :class="'xw-float-W' + Number(item.imgs.length)" v-for="(son, num) in item.imgs">
                <div class="LUR-img-three" :style="setTrueStyleThree"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + son.image + ')' }"></div></div>
              </dd>  
              </template>
            </dl>
            <div class="LUR-info xw-color-13 xw-flex xw-flex-align xw-flex-justify">
              <div class="LUR-time xw-flex-W1 xw-flex xw-flex-align">
                <em class="fa fa-clock" v-if="item.date"></em>{{item.date}} 
              </div>
              <div class="LUR-time xw-flex xw-flex-align">
                <em class="fa fa-eye"></em>{{item.views}}次
              </div>
            </div>
            <div class="LUR-btns xw-flex xw-flex-align xw-flex-justify">
              <div class="xw-btn xw-WBlue" @click="getAuditFun(1, item)">修改</div>
              <div class="xw-btn xw-WBlue" @click="getAuditFun(3, item)">删除</div>
              <div class="xw-btn xw-WBlue" @click="getAuditFun(4, item)">刷新</div>
              <div class="xw-btn" :class="[item.isCheck ? 'xw-WBlue' : 'xw-Gray']" @click="getAuditFun(5, item)">{{item.btnTxt}}</div>
              <div :class="item.checkStyle">{{item.checkTxt}}</div>
            </div>
          </a></li>
          <div class="list-li" :class="fold.class"><div ref="forTrueHeight">{{fold.info}}</div></div>
        </ul>
      </div>
    </div>
    <preImg-view ref="preImg"/>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>

<style scoped>
/* ---- */
.list-user li { position: relative; margin: 1rem 1rem 0; overflow: hidden; }
.list-user li:nth-of-type(1) { margin-top: 0; }
.list-user li > a { display: block; padding: 1.2rem 1rem; }
.LUR-title { margin: 0 0 0.8rem; line-height: 2.5rem; font-size: 1.7rem; font-weight: bold; text-align: justify; }
.LUR-con { padding: 0 0 1rem; }
.LUR-img-one { margin-right: 1rem; width: 6rem; height: 6rem; }
.LUR-advs { margin: 0 -0.2rem; padding: 0 0 0.8rem; }
.LUR-advs dd { margin: 0 0 0.4rem; }
.LUR-img-two, .LUR-img-three { margin: 0 0.2rem; }
.LUR-info { margin: 0 0 1rem; }
.LUR-time em { margin-right: 0.5rem; }
.list-li { margin: 0 1rem; padding: 0 1rem; }
.list-li div { min-height: 2rem; line-height: 2rem; text-align: justify; }
.list-li-one { padding-left: 8rem; }
</style>
